<template>
  <div class="confirm-order-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar title="确认订单" left-arrow @click-left="handleGoBack" />

    <!-- 服务保障栏 -->
    <div class="service-guarantee">
      <span class="guarantee-title">服务保障</span>
      <span class="guarantee-tags">明码标价 | 未上门随时退 | 30天质保</span>
    </div>

    <!-- 服务地址 -->
    <van-cell
      title="服务地址"
      :value="serviceAddress"
      is-link
      @click="showAddressPopup = true"
    />

    <!-- 上门时间选择 -->
    <van-cell
      title="上门时间"
      :value="selectedTimeLabel || '请选择上门时间'"
      is-link
      @click="showTimePopup = true"
    />

    <!-- 物品类型选择（单选） -->
    <van-cell
      title="物品类型"
      :value="selectedItemType || '请选择'"
      is-link
      @click="showItemTypePopup = true"
    />

    <!-- 维修类型选择（多选） -->
    <van-cell
      title="维修类型"
      :value="selectedRepairTypes.length > 0 ? selectedRepairTypes.join('、') : '请选择'"
      is-link
      @click="showRepairTypePopup = true"
    />

    <!-- 物品图片上传 -->
    <div class="item-image-section">
      <h3 class="section-title">物品图片</h3>
      <p class="hint-text">请拍清故障部位（柜面、滑轨、铰链等），便于师傅报价</p>
      <van-uploader
        v-model="uploadedImages"
        multiple
        :max-count="5"
        :after-read="handleImageUpload"
        @delete="handleImageDelete"
      />
    </div>

    <!-- 需求说明 -->
    <div class="demand-description">
      <h3 class="section-title">需求说明</h3>
      <p class="tip-text">请详细描述维修需求，以便师傅提供准确报价</p>
      <van-field
        type="textarea"
        rows="4"
        placeholder="示例：双开门衣柜左边柜门关不严，右边门卡死…"
        v-model="demandDesc"
        maxlength="999"
        show-word-limit
      />
    </div>

    <!-- PICC保障说明 -->
    <van-cell
      title="PICC保障"
      :value="insuranceDesc"
      is-link
      @click="navToInsurancePage"
    />

    <!-- 底部提交区域 -->
    <div class="submit-area">
      <div class="progress-tag">报价进度已完成90%</div>
    <van-button type="primary" size="large" @click="submitOrder" :loading="submitting">
        {{ submitting ? (route.query.isModify === 'true' ? '修改中...' : '提交中...') : (route.query.isModify === 'true' ? '确认修改' : '立即发布，获得附近师傅报价') }}
    </van-button>
    </div>

    <!-- 地址选择弹窗 -->
    <van-popup v-model:show="showAddressPopup" position="bottom">
      <div class="popup-inner">
        <div class="popup-header">
          <h2>选择服务地址</h2>
          <van-icon name="close" @click="showAddressPopup = false" />
        </div>
        <van-cell title="正义路2号北京市人民政府(旧址)" is-link @click="selectAddress" />
      </div>
    </van-popup>

    <!-- 上门时间选择弹窗 -->
    <van-popup v-model:show="showTimePopup" position="bottom">
      <div class="popup-inner">
        <div class="popup-header">
          <h2>选择上门时间</h2>
          <van-icon name="close" @click="showTimePopup = false" />
        </div>
        <van-cell 
          v-for="time in availableTimes" 
          :key="time.value"
          :title="time.label" 
          is-link 
          @click="selectTime(time.value)" 
        />
      </div>
    </van-popup>

    <!-- 物品类型弹窗（单选） -->
    <van-popup
      v-model:show="showItemTypePopup"
      position="bottom"
      :style="{ height: '60%' }"
    >
      <div class="popup-inner">
        <div class="popup-header">
          <h2>物品类型 <span class="popup-tag">单选</span></h2>
          <van-icon name="close" @click="showItemTypePopup = false" />
        </div>
        <div class="popup-list">
          <div v-if="itemTypes.length === 0" class="empty-hint">
            <p>暂无物品类型数据</p>
          </div>
          <van-cell
            v-for="type in itemTypes"
            :key="type.itemId"
            :title="type.itemName"
            is-link
            @click="selectItemType(type)"
          />
        </div>
      </div>
    </van-popup>

    <!-- 维修类型弹窗（多选） -->
    <van-popup
      v-model:show="showRepairTypePopup"
      position="bottom"
      :style="{ height: '60%' }"
    >
      <div class="popup-inner">
        <div class="popup-header">
          <h2>维修类型 <span class="popup-tag">多选</span></h2>
          <van-icon name="close" @click="showRepairTypePopup = false" />
        </div>
        <div class="popup-list">
          <div v-if="repairTypes.length === 0" class="empty-hint">
            <p>暂无维修类型数据 (数组长度: {{ repairTypes.length }})</p>
            <p>数据内容: {{ JSON.stringify(repairTypes) }}</p>
          </div>
         
          
          <!-- 最简化版本：完全模仿物品类型 -->
          <van-cell
            v-for="type in repairTypes"
            :key="`${type.typeId}-${forceUpdate}`"
            :title="type.typeName"
            is-link
            @click="toggleRepairType(type.typeName)"
          />
          
         
        </div>
        <div class="popup-footer">
          <van-button type="primary" @click="confirmRepairTypes">确认</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import {
  NavBar, Cell, Icon, Uploader, Field, Popup, CheckboxGroup, Checkbox, Button, showToast
} from 'vant';
import { 
  getRepairTypes, 
  getItemTypes, 
  createOrder, 
  updateOrder,
  getFastestArrivalTime,
  uploadImageApi 
} from '@/api';
import { useUserStore } from '@/stores/user';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

// 页面状态
const showAddressPopup = ref(false);
const showTimePopup = ref(false);
const showItemTypePopup = ref(false);
const showRepairTypePopup = ref(false);
const submitting = ref(false);

// 地址相关
const serviceAddress = ref('');
const selectedTime = ref('');

// 从CabinetRepair页面传递的参数
const passedAddress = computed(() => route.query.address);
const passedProvinceId = computed(() => route.query.provinceId);
const passedCityId = computed(() => route.query.cityId);
const passedProvinceName = computed(() => route.query.provinceName);
const passedCityName = computed(() => route.query.cityName);

// 物品类型相关
const itemTypes = ref([]);
const selectedItemType = ref('');

// 维修类型相关
const repairTypes = ref([]);
const selectedRepairTypes = ref([]);
const forceUpdate = ref(0); // 强制更新计数器

// 图片上传
const uploadedImages = ref([]);
const uploadedImageUrls = ref([]);

// 需求说明
const demandDesc = ref('');

// 可用上门时间
const availableTimes = ref([]);
const selectedTimeLabel = ref('');

// 初始化页面数据
onMounted(async () => {
  // 先检查是否是修改订单模式
  const isModifyMode = await checkAndHandleModifyMode();
  await initPageData();
  
  // 只有在非修改模式下才从查询参数初始化地址
  if (!isModifyMode) {
    initAddressFromQuery();
  }
  
  calculateAvailableTimes();
});

// 检查并处理修改订单模式
const checkAndHandleModifyMode = async () => {
  const isModify = route.query.isModify;
  const orderDataStr = route.query.orderData;
  
  if (isModify === 'true' && orderDataStr) {
    try {
      console.log('=== 修改订单模式 ===');
      const orderData = JSON.parse(decodeURIComponent(orderDataStr));
      console.log('解析的订单数据:', orderData);
      
      // 回填基本信息
      if (orderData.address) {
        serviceAddress.value = orderData.address;
        console.log('回填地址:', orderData.address);
      }
      selectedItemType.value = orderData.itemType || '';
      demandDesc.value = orderData.demandDescription || '';
      
      // 回填维修类型（需要解析JSON字符串）
      if (orderData.repairTypes) {
        try {
          const repairTypesArray = JSON.parse(orderData.repairTypes);
          selectedRepairTypes.value = Array.isArray(repairTypesArray) ? repairTypesArray : [];
        } catch (e) {
          console.warn('解析维修类型失败:', e);
          selectedRepairTypes.value = [];
        }
      }
      
      // 回填图片（需要解析JSON字符串）
      if (orderData.pictures) {
        try {
          const picturesArray = JSON.parse(orderData.pictures);
          if (Array.isArray(picturesArray) && picturesArray.length > 0) {
            // 这里需要根据实际情况处理图片回填
            uploadedImageUrls.value = picturesArray;
            // 创建假的上传图片对象用于显示
            uploadedImages.value = picturesArray.map((url, index) => ({
              url: url,
              uid: `existing-${index}`,
              status: 'done'
            }));
          }
        } catch (e) {
          console.warn('解析图片失败:', e);
        }
      }
      
      // 回填服务时间
      if (orderData.serviceTime) {
        // 这里需要根据服务时间找到对应的时间段
        const serviceDate = new Date(orderData.serviceTime);
        const timeValue = findTimeSlotByDate(serviceDate);
        selectedTime.value = timeValue;
        selectedTimeLabel.value = formatTimeSlotLabel(serviceDate);
      }
      
      console.log('数据回填完成');
      showToast('订单数据已回填');
      return true; // 返回true表示是修改模式
      
    } catch (error) {
      console.error('处理修改订单数据失败:', error);
      showToast('订单数据解析失败');
      return true; // 即使出错也返回true，避免地址被覆盖
    }
  }
  
  return false; // 返回false表示不是修改模式
};

// 根据日期查找对应的时间段值
const findTimeSlotByDate = (date) => {
  const hour = date.getHours();
  const today = new Date();
  const isToday = date.toDateString() === today.toDateString();
  const dayPrefix = isToday ? 'today' : 'tomorrow';
  
  // 根据小时找到对应的时间段
  const timeSlots = [8, 10, 12, 14, 16, 18, 20, 22];
  const matchingSlot = timeSlots.find(slot => slot === hour) || hour;
  
  return `${dayPrefix}_${matchingSlot}_0`;
};

// 格式化时间段标签
const formatTimeSlotLabel = (date) => {
  const today = new Date();
  const isToday = date.toDateString() === today.toDateString();
  const dayLabel = isToday ? '今天' : '明天';
  const hour = date.getHours();
  const endHour = hour + 2;
  
  return `${dayLabel} ${hour.toString().padStart(2, '0')}:00-${endHour.toString().padStart(2, '0')}:00`;
};

// 初始化页面数据
const initPageData = async () => {
  try {
    // 获取维修类型
    console.log('开始获取维修类型...');
    const repairResponse = await getRepairTypes();
    console.log('维修类型API响应:', repairResponse);
    repairTypes.value = repairResponse.data || [];
    console.log('设置维修类型数据:', repairTypes.value);
    
    // 获取物品类型
    console.log('开始获取物品类型...');
    const itemResponse = await getItemTypes();
    console.log('物品类型API响应:', itemResponse);
    itemTypes.value = itemResponse.data || [];
    console.log('设置物品类型数据:', itemTypes.value);
    
    // 计算最快上门时间
    if (passedCityId.value) {
      const timeResponse = await getFastestArrivalTime(passedCityId.value);
      const fastestTime = timeResponse.data || 4; // 默认4小时
      calculateAvailableTimes(fastestTime);
    } else {
      calculateAvailableTimes(4);
    }
  } catch (error) {
    console.error('初始化数据失败:', error);
    showToast('数据加载失败，请重试');
  }
};

// 从路由参数初始化地址
const initAddressFromQuery = () => {
  if (passedAddress.value) {
    serviceAddress.value = passedAddress.value;
  } else if (passedProvinceName.value && passedCityName.value) {
    serviceAddress.value = `${passedProvinceName.value}${passedCityName.value}`;
  } else {
    serviceAddress.value = '请选择服务地址';
  }
};

// 计算可用上门时间
const calculateAvailableTimes = (fastestTime = 4) => {
  const now = new Date();
  const currentHour = now.getHours();
  
  availableTimes.value = [];
  
  try {
    // 计算最早可预约时间
    const earliestTime = new Date(now.getTime() + fastestTime * 60 * 60 * 1000);
    
    // 如果最早时间还在今天22点之前，可以预约今天
    if (earliestTime.getHours() < 22) {
      const todaySlots = generateSimpleTimeSlots(earliestTime, true);
      availableTimes.value.push(...todaySlots);
    }
    
    // 生成明天的时间段（8:00-22:00）
    const tomorrowSlots = generateSimpleTimeSlots(null, false);
    availableTimes.value.push(...tomorrowSlots);
  } catch (error) {
    console.error('计算时间段出错:', error);
    // 提供备用时间段
    availableTimes.value = [
      { label: '明天 08:00-10:00', value: 'tomorrow_8_0', actualTime: null },
      { label: '明天 10:00-12:00', value: 'tomorrow_10_0', actualTime: null },
      { label: '明天 14:00-16:00', value: 'tomorrow_14_0', actualTime: null },
      { label: '明天 16:00-18:00', value: 'tomorrow_16_0', actualTime: null }
    ];
  }
};

// 简化的时间段生成函数
const generateSimpleTimeSlots = (startTime, isToday) => {
  const slots = [];
  const dayLabel = isToday ? '今天' : '明天';
  const now = new Date();
  
  // 预定义的时间段
  const timeSlots = [
    { start: 8, end: 10 },
    { start: 10, end: 12 },
    { start: 12, end: 14 },
    { start: 14, end: 16 },
    { start: 16, end: 18 },
    { start: 18, end: 20 },
    { start: 20, end: 22 }
  ];
  
  console.log(`生成时间段 - 是否今天: ${isToday}, 开始时间: ${startTime ? startTime.toLocaleString() : '无'}`);
  
  timeSlots.forEach(slot => {
    const actualTime = new Date();
    
    if (!isToday) {
      // 明天的时间
      actualTime.setDate(now.getDate() + 1);
    } else {
      // 今天的时间
      actualTime.setDate(now.getDate());
    }
    actualTime.setHours(slot.start, 0, 0, 0);
    
    // 时间段结束时间
    const slotEndTime = new Date(actualTime);
    slotEndTime.setHours(slot.end, 0, 0, 0);
    
    // 检查时间段是否可用
    let isAvailable = true;
    
    if (isToday) {
      // 对于今天的时间段，需要检查：
      // 1. 时间段结束时间必须在当前时间之后
      // 2. 如果有最早可预约时间，时间段开始时间必须在最早时间之后
      const currentTime = new Date();
      
      if (slotEndTime <= currentTime) {
        // 时间段已经过去了
        isAvailable = false;
        console.log(`时间段 ${slot.start}:00-${slot.end}:00 已过去，跳过`);
      } else if (startTime && actualTime < startTime) {
        // 时间段开始时间早于最早可预约时间
        isAvailable = false;
        console.log(`时间段 ${slot.start}:00-${slot.end}:00 早于最早可预约时间，跳过`);
      }
    }
    
    if (isAvailable) {
      console.log(`创建时间段: ${slot.start}:00-${slot.end}:00, actualTime: ${actualTime.toISOString()}`);
      
      slots.push({
        label: `${dayLabel} ${slot.start.toString().padStart(2, '0')}:00-${slot.end.toString().padStart(2, '0')}:00`,
        value: `${isToday ? 'today' : 'tomorrow'}_${slot.start}_0`,
        actualTime: actualTime
      });
    }
  });
  
  console.log('生成的时间段:', slots);
  return slots;
};

// 格式化时间
const formatTime = (baseTime, hoursToAdd) => {
  const targetTime = new Date(baseTime.getTime() + hoursToAdd * 60 * 60 * 1000);
  const hours = targetTime.getHours().toString().padStart(2, '0');
  const minutes = targetTime.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
};

// 地址选择
const selectAddress = () => {
  showAddressPopup.value = false;
};

// 时间选择
const selectTime = (timeValue) => {
  selectedTime.value = timeValue;
  // 找到对应的时间标签
  const timeOption = availableTimes.value.find(t => t.value === timeValue);
  selectedTimeLabel.value = timeOption ? timeOption.label : timeValue;
  showTimePopup.value = false;
};

// 物品类型选择
const selectItemType = (item) => {
  selectedItemType.value = item.itemName;
  showItemTypePopup.value = false;
};

// 维修类型选择
const toggleRepairType = (typeName) => {
  const index = selectedRepairTypes.value.indexOf(typeName);
  if (index > -1) {
    selectedRepairTypes.value.splice(index, 1);
  } else {
    selectedRepairTypes.value.push(typeName);
  }
};

const confirmRepairTypes = () => {
  showRepairTypePopup.value = false;
};

// 测试加载维修类型
const testLoadRepairTypes = async () => {
  try {
    console.log('测试加载维修类型...');
    console.log('当前repairTypes.value:', repairTypes.value);
    showToast('开始测试加载维修类型');
    
    const response = await getRepairTypes();
    console.log('测试API响应:', response);
    
    if (response && response.data) {
      repairTypes.value = response.data;
      console.log('设置后的repairTypes.value:', repairTypes.value);
      console.log('repairTypes.value.length:', repairTypes.value.length);
      console.log('第一个元素:', repairTypes.value[0]);
      
      // 强制触发响应式更新
      forceUpdate.value++;
      await nextTick();
      console.log('nextTick后的repairTypes.value:', repairTypes.value);
      console.log('forceUpdate.value:', forceUpdate.value);
      
      showToast(`成功加载 ${response.data.length} 个维修类型`);
    } else {
      showToast('API响应格式异常');
    }
  } catch (error) {
    console.error('测试加载失败:', error);
    showToast('测试加载失败: ' + error.message);
  }
};

// 图片上传处理
const handleImageUpload = async (file) => {
  try {
    const formData = new FormData();
    formData.append('image', file.file);
    
    const response = await uploadImageApi(formData);
    
    if (response.code === 200 && response.data && response.data.url) {
      uploadedImageUrls.value.push(response.data.url);
      showToast('图片上传成功');
    } else {
      showToast('图片上传失败：' + (response.message || '未知错误'));
      // 移除失败的图片
      const index = uploadedImages.value.findIndex(item => item.file === file.file);
      if (index > -1) {
        uploadedImages.value.splice(index, 1);
      }
    }
  } catch (error) {
    console.error('图片上传异常:', error);
    showToast('图片上传失败');
    // 移除失败的图片
    const index = uploadedImages.value.findIndex(item => item.file === file.file);
    if (index > -1) {
      uploadedImages.value.splice(index, 1);
    }
  }
};

// 图片删除处理
const handleImageDelete = (file) => {
  const index = uploadedImages.value.findIndex(item => item.uid === file.uid);
  if (index > -1) {
    uploadedImages.value.splice(index, 1);
    uploadedImageUrls.value.splice(index, 1);
  }
};

// PICC保障
const insuranceDesc = ref('本服务由中国人保全程保障您的人身财产安全');
const navToInsurancePage = () => {
  router.push('/insurance');
};

// 提交订单
const submitOrder = async () => {
  // 防重复提交
  if (submitting.value) {
    console.log('正在提交中，请勿重复点击');
    return;
  }

  console.log('开始提交维修订单');
  
  // 表单验证
  if (!selectedItemType.value) {
    showToast('请选择物品类型');
    return;
  }
  if (selectedRepairTypes.value.length === 0) {
    showToast('请选择维修类型');
    return;
  }
  if (uploadedImages.value.length === 0) {
    showToast('请上传物品图片');
    return;
  }
  if (!demandDesc.value.trim()) {
    showToast('请填写需求说明');
    return;
  }
  if (!selectedTime.value) {
    showToast('请选择上门时间');
    return;
  }

  submitting.value = true;

  try {
    // 处理上门时间 - 根据用户选择的时间段
    let serviceTime = null;
    if (selectedTime.value) {
      console.log('=== 处理上门时间开始 ===');
      console.log('用户选择的时间值:', selectedTime.value);
      console.log('可用时间列表数量:', availableTimes.value.length);
      
      // 从选择的时间段中获取实际时间
      const selectedTimeSlot = availableTimes.value.find(t => t.value === selectedTime.value);
      console.log('找到的时间段:', selectedTimeSlot);
      
      if (selectedTimeSlot && selectedTimeSlot.actualTime) {
        serviceTime = new Date(selectedTimeSlot.actualTime.getTime());
        console.log('使用actualTime:', serviceTime);
        console.log('actualTime的ISO字符串:', serviceTime.toISOString());
        console.log('actualTime的本地时间:', serviceTime.toLocaleString());
      } else {
        // 备用处理逻辑
        console.warn('未找到时间段，使用备用逻辑');
        const now = new Date();
        const timeValue = selectedTime.value;
        console.log('使用备用逻辑，timeValue:', timeValue);
        
        if (timeValue.startsWith('today_')) {
          const parts = timeValue.split('_');
          const hour = parseInt(parts[1]) || 8;
          const minute = parseInt(parts[2]) || 0;
          serviceTime = new Date();
          serviceTime.setHours(hour, minute, 0, 0);
          console.log('今天时间:', serviceTime);
        } else if (timeValue.startsWith('tomorrow_')) {
          const parts = timeValue.split('_');
          const hour = parseInt(parts[1]) || 8;
          const minute = parseInt(parts[2]) || 0;
          serviceTime = new Date();
          serviceTime.setDate(serviceTime.getDate() + 1);
          serviceTime.setHours(hour, minute, 0, 0);
          console.log('明天时间:', serviceTime);
        } else {
          console.error('无法识别的时间格式:', timeValue);
        }
      }
      
      console.log('最终服务时间:', serviceTime);
      console.log('最终服务时间ISO:', serviceTime ? serviceTime.toISOString() : null);
      console.log('=== 处理上门时间结束 ===');
    }

    const orderData = {
      address: serviceAddress.value,
      serviceTime: serviceTime ? formatDateForBackend(serviceTime) : null,
      itemType: selectedItemType.value,
      repairTypes: JSON.stringify(selectedRepairTypes.value),
      demandDescription: demandDesc.value,
      pictures: JSON.stringify(uploadedImageUrls.value),
      provinceId: parseInt(passedProvinceId.value) || null,
      cityId: parseInt(passedCityId.value) || null,
      fastestArrivalTime: 4, // 从API获取的实际值
      serviceId: 1, // 柜类维修的服务ID
      userId: parseInt(userStore.id) || 1 // 当前登录用户ID
    };

    // 检查是否是修改模式
    const isModify = route.query.isModify === 'true';
    let response;
    
    if (isModify) {
      // 修改订单模式
      const originalOrderData = JSON.parse(decodeURIComponent(route.query.orderData));
      response = await updateOrder(originalOrderData.orderId, orderData);
    } else {
      // 创建新订单模式
      response = await createOrder(orderData);
    }
    
    console.log('维修订单API响应:', response);
    
    if (response && response.code === 200) {
      if (isModify) {
        showToast('订单修改成功！');
        console.log('维修订单修改成功，准备跳转');
        setTimeout(() => {
          const orderId = JSON.parse(decodeURIComponent(route.query.orderData)).orderId;
          console.log('跳转到等待报价页面，订单ID:', orderId);
          router.push({
            path: '/waiting-quote',
            query: { orderId: orderId }
          });
        }, 800); // 缩短等待时间
      } else {
        showToast('订单提交成功！');
        console.log('维修订单创建成功，订单ID:', response.data);
        setTimeout(() => {
          router.push({
            path: '/waiting-quote',
            query: { orderId: response.data }
          });
        }, 800); // 缩短等待时间
      }
    } else {
      console.error('维修订单提交失败，响应:', response);
      const errorMsg = (response && response.message) || '订单提交失败，请重试';
      showToast(errorMsg);
    }
  } catch (error) {
    console.error('维修订单提交异常:', error);
    let errorMessage = '网络错误，请检查网络连接后重试';
    
    // 根据不同错误类型给出不同提示
    if (error.response) {
      if (error.response.status === 404) {
        errorMessage = '服务接口未找到，请联系技术支持';
      } else if (error.response.status === 500) {
        errorMessage = '服务器内部错误，请稍后重试';
      } else {
        errorMessage = `请求失败 (${error.response.status})，请重试`;
      }
    } else if (error.code === 'NETWORK_ERROR') {
      errorMessage = '网络连接失败，请检查网络后重试';
    }
    
    showToast(errorMessage);
  } finally {
    submitting.value = false;
  }
};

// 格式化时间给后端使用
const formatDateForBackend = (date) => {
  // 确保传递正确的ISO格式时间字符串
  if (!date) return null;
  
  console.log('格式化前的时间对象:', date);
  console.log('时间对象类型:', typeof date);
  console.log('是否为Date对象:', date instanceof Date);
  
  // 如果是Date对象，转换为ISO字符串
  if (date instanceof Date) {
    const isoString = date.toISOString();
    console.log('转换后的ISO字符串:', isoString);
    return isoString;
  }
  
  // 如果已经是字符串，直接返回
  if (typeof date === 'string') {
    console.log('已经是字符串，直接返回:', date);
    return date;
  }
  
  console.warn('未知的时间格式:', date);
  return null;
};

// 返回上一页
const handleGoBack = () => {
  router.back();
};
</script>

<style scoped>
/* 保持原有的样式不变 */
.confirm-order-page {
  background-color: #fff;
  min-height: 100vh;
  padding-bottom: 80px;
  box-sizing: border-box;
}

.service-guarantee {
  background-color: #e6f7ff;
  padding: 10px 16px;
  display: flex;
  align-items: center;
}
.guarantee-title {
  font-weight: bold;
  color: #ff4545;
  margin-right: 10px;
}
.guarantee-tags {
  color: #666;
  font-size: 14px;
}

.item-image-section,
.demand-description {
  padding: 16px;
  border-bottom: 1px solid #eee;
}
.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}
.hint-text {
  font-size: 14px;
  color: #999;
  margin-bottom: 12px;
}
.tip-text {
  color: #ff6600;
  font-size: 14px;
  margin-bottom: 8px;
}

.submit-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 16px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
}
.progress-tag {
  display: inline-block;
  background-color: #ffd799;
  color: #ff6600;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
  margin-bottom: 8px;
}

.popup-inner {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.popup-header {
  padding: 16px;
  border-bottom: 1px solid #eee;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}
.popup-header h2 {
  font-size: 18px;
  font-weight: bold;
}
.popup-header .van-icon {
  position: absolute;
  right: 16px;
  font-size: 24px;
  cursor: pointer;
}
.popup-tag {
  font-size: 12px;
  color: #fff;
  background-color: #f39800;
  padding: 2px 6px;
  border-radius: 4px;
  margin-left: 8px;
}
.popup-list {
  max-height: calc(60% - 120px);
  overflow-y: auto;
  padding: 8px 0;
}
.popup-footer {
  padding: 16px;
}

.empty-hint {
  padding: 40px 16px;
  text-align: center;
  color: #999;
}
</style>